<?php

/**
 * 每天定时检查待完善信息状态的wiki，同时添加抓取任务，重新抓取wiki信息
 */

ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\brand\CustomCategoryWiki as mCustomCategoryWiki;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\model\wiki\WikiContent as mWikiContent;
use Biz\module\Classes\wiki\RelateWiki as clsRelateWiki;
use Biz\service\Album\AlbumWikiListService;
use Biz\service\wiki\WikiBasic;
use Biz\tools\RealUrl;

scraperNormalWiki();
delNormalWiki();
repairEmptyTitleWiki();
delEmptyWikiCategory();

function scraperNormalWiki($lastDay = 5)
{
    $time = date("Y-m-d", strtotime("-" . $lastDay . " day"));
    $wikiList = mWiki::selectByWhere(['status' => mWiki::STATUS_NORMAL, 'addtime[>=]' => $time, 'ORDER' => ['id' => 'DESC']]);
    var_dump('待完善资料的wiki商品数量为：' . count($wikiList));
    if (count($wikiList) > 50) {
        \Biz\tools\Mail::send(['tangyiwan@haohaozhu.com'], '待完善资料的wiki商品数量为：' . count($wikiList), '待完善资料的wiki商品数量为：' . count($wikiList));
    }
    foreach ($wikiList as $row) {
        $contentInfo = \Biz\model\wiki\WikiContent::getByWhere(['wiki_id' => $row['id']], ['wiki_id', 'imgs', 'content']);
        $row['imgs'] = $contentInfo ? $contentInfo['imgs'] : '';
        $row['content'] = $contentInfo ? $contentInfo['content'] : '';
        $itemId = $row['channel_spu_id'];
        $type = $row['channel_type'];
        if (!$row['title'] || !$row['cover_img']
            || (!$row['channel_shop_id'] && !$row['channel_seller_id'])
            || !$row['channel_shop_name']
            || $row['min_price'] <= 0 || $row['max_price'] <= 0
            || !$row['imgs'] || !$row['content']) {
            $url = RealUrl::formatLink($itemId, $type, $row['channel_jump_params'], $row['channel_shop_id']);
            if ($url) {
                var_dump(date('YmdH:i:s') . '开始同步wiki#wiki_id:' . $row['id'] . '#url:' . $url);
                $wikiInfo = \Biz\service\wiki\Wiki::getWikiByLink($url, null);
            }
        } else {
            var_dump('已完善商品信息#wiki_id:' . $row['id']);
            mWiki::updateData(['status' => mWiki::STATUS_WAIT_CHECK], ['id' => $row['id'], 'status' => mWiki::STATUS_NORMAL]);
        }
    }
}

function delNormalWiki($lastDay = 3)
{
    //多少天天前还是待完善资料的wiki删除掉，同时删除wiki关联
    $endTime = date("Y-m-d H:i:s", strtotime("-" . $lastDay . " day"));
    $wikiList = mWiki::selectByWhere(['status' => mWiki::STATUS_NORMAL, 'addtime[<]' => $endTime]);
    $wikiIds = array_column($wikiList, 'id');
    var_dump('检查超过' . $lastDay . '天还是待完善资料的wiki数：' . count($wikiIds));
    if ($wikiList && $wikiIds) {
        foreach ($wikiList as $row) {
            if (!$row['title'] || !$row['cover_img'] || $row['min_price'] <= 0 || $row['max_price'] <= 0) {
                //待完善资料，如果标题，图片，价格都没有，则删除
                $relateList = mObjRelateWiki::getByWhere(['wiki_id' => $row['id'], 'status' => mObjRelateWiki::STATUS_NORMAL]);
                var_dump('wiki超过' . $lastDay . '天还是待完善资料的，需要删除' . $row['id']);
                mWiki::updateData(['status' => mWiki::STATUS_DEL], ['id' => $row['id']]);
                mWikiContent::updateData(['operator' => 0], ['wiki_id' => $row['id']]);
                var_dump('解除wiki的所有关联' . $row['id']);
                mObjRelateWiki::updateData(['status' => mObjRelateWiki::STATUS_DEL], ['wiki_id' => $row['id'], 'status' => mObjRelateWiki::STATUS_NORMAL]);
                foreach ($relateList as $row) {
                    $uid = $row['uid'];
                    $wikiId = $row['wiki_id'];
                    $objId = $row['obj_id'];
                    $objType = $row['obj_type'];
                    var_dump('更新wiki#' . $wikiId . '的关联数量及用户清单');
                    clsRelateWiki::afterRelateWiki($uid, [$wikiId], $objId, $objType);
                }
                AlbumWikiListService::afterOffLineWiki($wikiId);
            }
        }
    }
    foreach ($wikiList as $row) {
        if ($row['basic_id']) {
            WikiBasic::afterChangeBasic([$row['basic_id']], $row['brand_id']);
        }
    }
}

function repairEmptyTitleWiki($lastDay = 4)
{
    //title 为空的wiki basic
    $endTime = date("Y-m-d", strtotime("-" . $lastDay . " day"));
    $list = mWikiBasic::selectByWhere(['title' => '', 'basic_state[!]' => mWikiBasic::STATE_DEL, 'addtime[<]' => $endTime]);
    var_dump('检查超过' . $lastDay . '天wiki_basic.title为空的数：' . count($list));
    foreach ($list as $row) {
        $info = mWiki::getByWhere(['basic_id' => $row['id'], 'is_default' => 1]);
        if ($info) {
            $data['title'] = $info['title'];
            if (!$row['category_id']) {
                $data['category_id'] = $info['category_id'];
                $data['second_category_id'] = $info['second_category_id'];
                $data['third_category_id'] = $info['third_category_id'];
                $data['four_category_id'] = $info['four_category_id'];
                $data['last_category_id'] = $info['last_category_id'];
            }
            mWikiBasic::updateData($data, ['id' => $row['id']]);
        }
    }
}


function delEmptyWikiCategory()
{
    $hour = date('H');
    if ($hour < 3) {
        //没有商品的wiki basic 给删除掉
        var_dump('检查没有商品的wiki basic');
        $sql = 'SELECT id FROM ' . mWikiBasic::_TABLE_NAME . ' 
                WHERE basic_state!=9 AND 
                id NOT IN (
                SELECT basic_id FROM ' . mWiki::_TABLE_NAME . ' )';
        $res = mWikiBasic::query($sql)->fetchAll();
        var_dump(mWikiBasic::log());
        $basicIds = $res ? array_column($res, 'id') : [];
        var_dump('basic ids:' . count($basicIds));
        $allCount = 0;
        foreach ($basicIds as $basicId) {
            $count = mWiki::selectCountWhere(['basic_id' => $basicId]);
            if (!$count) {
                var_dump($basicId . '的商品数为:' . $count . '需要删除');
                mWikiBasic::updateData(['basic_state' => mWikiBasic::STATE_DEL], ['id' => $basicId]);
                mCustomCategoryWiki::updateData(['custom_state' => mCustomCategoryWiki::STATE_DEL], ['basic_id' => $basicId]);
                $allCount++;
            }
        }
        var_dump('没有商品的wiki basic 数量：' . $allCount);
    }
}